package com.bjpower.common.exceptions;

import com.bjpower.common.enums.SysCode;
import com.bjpower.common.exceptions.type.SysException;
import com.bjpower.models.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SysException.class)
    public Result sysExceptionHandler(SysException e) {
        return Result.error(e.getSysCode());
    }
    //添加Validation异常处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        StringBuffer stringBuffer = new StringBuffer();
        //获取错误对象集合
        List<FieldError> fieldErrors = e.getFieldErrors();
        //便利集合
        fieldErrors.forEach(fil ->{
            stringBuffer.append("错误项目:[" + fil.getCode() + "],错误名称：[" + fil.getDefaultMessage() + "]")
                    .append("#");
        });
        Result result = new Result();
        result.setCode(SysCode.REQUEST_PARAM_ERROR.getCode());
        result.setMessage(SysCode.REQUEST_PARAM_ERROR.getMessage() + "["+stringBuffer+"]");
        result.setData("");
        return result;
    }
}
